<?php
/**
 * 分页功能
 */
class Page
{	
	private $rowsPrePage;
	private $maxNum;
	private $rowsCount;
	private $url;

	public function __construct($rowsCount,$rowsPrePage,$maxNum,$url)
	{
		$this->initParam($rowsCount,$rowsPrePage,$maxNum,$url);
	}
	private function initParam($rowsCount,$rowsPrePage,$maxNum,$url)
	{
		$this->rowsCount=$rowsCount;
		$this->rowsPrePage=$rowsPrePage;
		$this->maxNum=$maxNum;
		$this->url=$url;
	}
	public function show()
	{
		//计算总页数
		$pages=ceil($this->rowsCount/$this->rowsPrePage);
		//获取当前页码数
		$pageNum=isset($_GET['pageNum']) ? $_GET['pageNum'] : 1;
		//定义页码字符串
		$strPage='';
		//首页
		$strPage="<a href='{$this->url}&pageNum=1'>首页</a>&nbsp;";
		//上一页
		$prePage=$pageNum-1;
		if ($pageNum>1) {
			$strPage.="<a href='{$this->url}&pageNum=$prePage'><<上一页</a>&nbsp;";
		}
		//中间页码
		//确定开始页码
		if($pageNum<=3)
		{
			$startNum=1;
		}
		else
		{
			$startNum=$pageNum-2;
		}
		if($startNum>=$pages-$this->maxNum+1)
		{
			$startNum=$pages-$this->maxNum+1;
		}
		if($startNum<1)
		{
			$startNum=1;
		}
		//确定结束的页码
		$endNum=$startNum+$this->maxNum-1;
		if($endNum>=$pages)
		{
			$endNum=$pages;
		}
		if($pages<=$this->maxNum)
		{
			$endNum=$pages;
		}
		for($i=$startNum;$i<=$endNum;$i++)
		{
			if($i==$pageNum)
			{
				$strPage.="<a href='{$this->url}&pageNum=$i'><font color='red'>$i</font></a>&nbsp;";
			}
			else
			{
				$strPage.="<a href='{$this->url}&pageNum=$i'>$i</a>&nbsp;";
			}
		}
		//拼凑下一页
		$nextNum=$pageNum+1;
		if ($nextNum<=$pages) {
			$strPage.="<a href='{$this->url}&pageNum=$nextNum'>下一页>></a>&nbsp;";
		}
		//尾页
		$strPage.="<a href='{$this->url}&pageNum=$pages'>尾页</a>&nbsp;";
		$strPage.="总页数:$pages";
		return $strPage;
	}
}